package com.startx.http.service.redis;

import java.util.Map;
import java.util.Objects;

import javax.inject.Inject;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import com.startx.core.system.param.HttpBody;
import com.startx.core.system.param.HttpParam;
import com.startx.http.dao.IDataEntryDao;
import com.startx.http.entity.data.DataEntry;
import com.startx.http.service.IDataEntryService;
import com.startx.http.system.cache.TokenCache;
import com.startx.http.system.constant.Constants;

@Service
public class DataEntryService implements IDataEntryService {
	
	@Inject
	private IDataEntryDao dataEntryDao;

	@Override
	public void doSaveDataEntry(HttpParam param, HttpBody body) {
		String token = param.getParam("token");
		String userId = TokenCache.getUserId(token);
		String cover = param.getParam("cover");
		
		DataEntry entry = new DataEntry();
		entry.setUserId(userId);
		entry.setEntry(body.getMap());
		
		if(StringUtils.isNotBlank(cover)) {
			dataEntryDao.save(entry);
		} else {
			dataEntryDao.saveOrUpdate(entry);
		}
	}

	@Override
	public Map<String,?> doGetDataEntry(HttpParam param) {
		String key = param.getParam("key");
		String token  = param.getParam("token");
		String userId = TokenCache.getUserId(token);
		
		Map<String,?> data = Constants.EMPTY_DICTIONARY;
		if(StringUtils.isBlank(key)) {
			//查询整个文档
			DataEntry entry = dataEntryDao.getById(userId);
			if(!Objects.isNull(entry)) {
				data = entry.getEntry();
			}
		} else {
			//查询某个文档
			data = dataEntryDao.getKeyValueByKey(userId,key);
		}
		
		return data;
	}

}
